package com.easyadmin.controller;

import com.easyadmin.annotation.GlobalInterceptor;
import com.easyadmin.config.AdminConfig;
import com.easyadmin.entity.enums.PermissionCodeEnum;
import com.easyadmin.utils.StringTools;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@RestController
@RequestMapping("/api/file")
public class FileController extends ABaseController {

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    @Resource
    private AdminConfig adminConfig;


    /**
     * @Description: 通用下载
     * @auther: 多多洛
     * @date: 21:57 2020/11/28
     * @param: [request, response, downloadFileName, fileName]
     * @return: void
     */
    @RequestMapping("download")
    @GlobalInterceptor(permissionCode = PermissionCodeEnum.NO_PERMISSION)
    public void download(HttpServletRequest request, HttpServletResponse response, String downloadFileName, String fileName) {
        InputStream in = null;
        OutputStream out = null;
        downloadFileName = StringTools.isEmpty(downloadFileName) ? fileName : downloadFileName;
        String filePath = adminConfig.getFileDownloadTemp() + fileName;
        File file = new File(filePath);
        try {
            in = new FileInputStream(file);
            out = response.getOutputStream();
            response.setContentType("application/x-msdownload; charset=UTF-8");
            // 解决中文文件名乱码问题
            if (request.getHeader("User-Agent").toLowerCase().indexOf("msie") > 0) {//IE浏览器
                downloadFileName = URLEncoder.encode(downloadFileName, "UTF-8");
            } else {
                downloadFileName = new String(downloadFileName.getBytes("UTF-8"), "ISO8859-1");
            }
            response.setHeader("Content-Disposition", "attachment;filename=\"" + downloadFileName + "\"");
            byte[] byteData = new byte[1024];
            int len = 0;
            while ((len = in.read(byteData)) != -1) {
                out.write(byteData, 0, len); // write
            }
            out.flush();
        } catch (Exception e) {
            logger.error("下载异常", e);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }

            } catch (IOException e) {
                logger.error("IO异常", e);
            }
            try {
                if (out != null) {
                    out.close();
                }

            } catch (IOException e) {
                logger.error("IO异常", e);
            }

            try {
                FileUtils.forceDelete(file);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
